<?php

namespace Home\Model;

use Think\Model;
use Home\Model\EmailModel;

class UserModel extends Model {
	public function _initialize() {
		$this->ApiPath = APP_PATH . '../Plugins/uc_client/';
		require_once APP_PATH . 'Common/Conf/uc_config.php';
		require_once $this->ApiPath . 'client.php';
		parent::_initialize ();
	}

	/**
	 * 登录
	 *
	 * @param unknown $username
	 * @param unknown $password
	 * @return boolean Ambigous mixed, multitype:, unknown>
	 */
	public function login($username, $password) {
		if (! $username || ! $password) {
			$this->error = '登录账号和密码不能空';
			return false;
		}
		$result = uc_user_login ( $username, $password );
		if ($result [0] == - 1) {
			$result = uc_user_login ( $username, $password, 2 );
		}
		list ( $uid, $username, $password, $email ) = $result;
		if ($uid > 0) {
			$result ['status'] = 1;
			$result ['msg'] = '登录成功';
		} elseif ($uid == - 1) {
			$result ['status'] = 0;
			$result ['msg'] = '用户不存在,或者被删除';
		} elseif ($uid == - 2) {
			$result ['status'] = 0;
			$result ['msg'] = '密码错误';
		} else {
			$result ['status'] = 0;
			$result ['msg'] = '未定义错误，请稍后重试';
		}
		if ($result ['status'] == 1) {
			// 登录
			add_cookie ( 'uid', $uid, array (
					'expire' => 3600 * 24 * 365
			) );
			// 添加到本地数据库
			$_data ['uid'] = $uid;
			$_data ['username'] = $username;
			$_data ['email'] = $email;
			$_data ['updateip'] = get_user_ip ();
			$_data ['updatetime'] = date ( 'Y-m-d H:i:s' );

			if ($this->_isHave ( $uid )) {

				$this->saveUser ( $_data, $uid );
			} else {
				$this->saveUser ( $_data );
			}
			$this->where ( 'uid=' . intval ( $uid ) )->setInc ( 'loginnum', 1 );
		}
		return $result;
	}
	public function logout() {
		add_cookie ( 'uid', null );
		$result ['status'] = 1;
		$result ['msg'] = '退出成功';
		return $result;
	}
	/**
	 * 用户注册
	 *
	 * @param unknown $username
	 * @param unknown $password
	 * @param unknown $email
	 * @return string
	 */
	public function register($username, $password, $email) {
		if (! $username || ! $email || ! $password) {
			$result ['status'] = 0;
			$result ['msg'] = '登录账号,邮箱和密码不能空';
		}
		if (strlen ( $username ) < 3) {
			$result ['status'] = 0;
			$result ['msg'] = '用户名长度必须大于3位';
		}
		if (strlen ( $password ) < 6) {
			$result ['status'] = 0;
			$result ['msg'] = '密码长度必须大于6位';
		}

		if ($result ['status'] == '0') {
			return $result;
		}
		$uid = uc_user_register ( $username, $password, $email, '', '', get_user_ip () );

		if ($uid > 0) {
			$result ['status'] = 1;
			$result ['msg'] = '注册成功';
		} elseif ($uid == - 1) {
			$result ['status'] = 0;
			$result ['msg'] = '用户名不合法';
		} elseif ($uid == - 2) {
			$result ['status'] = 0;
			$result ['msg'] = '包含要允许注册的词语';
		} elseif ($uid == - 3) {
			$result ['status'] = 0;
			$result ['msg'] = '用户名已经存在';
		} elseif ($uid == - 4) {
			$result ['status'] = 0;
			$result ['msg'] = 'Email 格式有误';
		} elseif ($uid == - 5) {
			$result ['status'] = 0;
			$result ['msg'] = 'Email 不允许注册';
		} elseif ($uid == - 6) {
			$result ['status'] = 0;
			$result ['msg'] = '该 Email 已经被注册';
		} else {
			$result ['status'] = 0;
			$result ['msg'] = '未定义错误，请稍后重试';
		}
		// 添加到本地数据库
		if ($uid > 0) {
			$_data ['createip'] = get_user_ip ();
			$_data ['createtime'] = date ( 'Y-m-d H:i:s' );
			$_data ['password'] = $password;
			$_data ['uid'] = $uid;
			$_data ['username'] = $username;
			$_data ['email'] = $email;

			$this->saveUser ( $_data );
			// 登录
			add_cookie ( 'uid', $uid, array (
					'expire' => 3600 * 24 * 1
			) );

			// 发送激活邮件
			$this->sendActivation ( $email );
		}
		return $result;
	}
	public function checkEmail($email) {
		$ucresult = uc_user_checkemail ( $email );
		if ($ucresult > 0) {
			$result ['status'] = 1;
			$result ['msg'] = 'Email 格式正确';
		} elseif ($ucresult == - 4) {
			$result ['status'] = 0;
			$result ['msg'] = 'Email 格式有误';
		} elseif ($ucresult == - 5) {
			$result ['status'] = 0;
			$result ['msg'] = 'Email 不允许注册';
		} elseif ($ucresult == - 6) {
			$result ['status'] = 0;
			$result ['msg'] = '该 Email 已经被注册';
		}
		return $result;
	}
	public function checkUserName($username) {
		$ucresult = uc_user_checkname ( $username );
		if ($ucresult > 0) {
			$result ['status'] = 1;
			$result ['msg'] = '用户名可用';
		} elseif ($ucresult == - 1) {
			$result ['status'] = 0;
			$result ['msg'] = '用户名不合法';
		} elseif ($ucresult == - 2) {
			$result ['status'] = 0;
			$result ['msg'] = '有不许注册的关键字';
		} elseif ($ucresult == - 3) {
			$result ['status'] = 0;
			$result ['msg'] = '用户名已经存在';
		}
		return $result;
	}
	public function isLogin($jumpUrl = '') {
		$uid = get_cookie ( 'uid' );
		if (! $uid) {
			jump ( url ( 'Public/login', array (
					'jumpUrl' => $jumpUrl ? $jumpUrl : getPageUrl ()
			) ) );
		} else {
			return $uid;
		}
	}
	public function getUserInfo($uid) {
		$uid = isset ( $uid ) ? intval ( $uid ) : get_cookie ( 'uid' );

		// 读取缓存
		$cacheName = get_cache_name ( 'user_' . $uid );
		$result = S ( $cacheName );
		if ($result) {
			return $result;
		}

		$data = uc_get_user ( $uid, 1 );
		if (! $data) {
			$data = uc_get_user ( $uid );
		}

		list ( $uid, $username, $email ) = $data;
		$result ['uid'] = $uid;
		$result['username'] = $username;
		$result['email'] = $email;
		$result['avatar'] = 'http://ucenter.fengqiaoju.com/avatar.php?uid='.intval($uid).'&size=small';

		S ( $cacheName, $result, C ( 'cache_time_long' ) );

		return $result;
	}
	public function getUserInfoForName($username) {
		$result = $this->where ( 'username="' . $username . '"' )->find ();
		return $result;
	}
	private function _getUserInfo($uid) {
		$result = $this->where ( 'uid=' . intval ( $uid ) )->find ();
		return $result;
	}
	/**
	 * 保存用户信息
	 *
	 * @param array $data
	 *        	用户信息
	 * @param int $uid
	 *        	用户id,如果存在则编辑;不存在则添加
	 * @return Ambigous <mixed, boolean, unknown, string>
	 */
	public function saveUser($data, $uid = '') {
		if ($uid) {
			unset ( $data ['uid'] ); // 禁止修改项
			unset ( $data ['createtime'] );
			unset ( $data ['createip'] );
			unset ( $data ['username'] );
			$_data ['updatetime'] = date ( 'Y-m-d H:i:s' );
			$_data ['updateip'] = get_user_ip ();
			if ($data ['email']) {
				$_data ['email'] = $data ['email'];
			}
			if ($data ['credit']) {
				$_data ['credit'] = $data ['credit'];
			}
			if ($data ['gold']) {
				$_data ['gold'] = $data ['gold'];
			}
			if ($data ['loginnum']) {
				$_data ['loginnum'] = $data ['loginnum'];
			}
			$result = $this->where ( 'uid=' . intval ( $uid ) )->save ( $_data );
			$this->_clearUserCache ( $uid );
		} else {
			unset ( $data ['updatetime'] ); // 禁止修改项
			unset ( $data ['updateip'] );
			if (! intval ( $data ['uid'] )) {
				$this->error = 'uid不能空';
			}
			if (! trim ( $data ['username'] )) {
				$this->error = '用户名不能空';
			}
			if (! trim ( $data ['email'] )) {
				$this->error = '邮箱不能空';
			}
			$_data ['uid'] = $data ['uid'];
			$_data ['username'] = $data ['username'];
			$_data ['email'] = $data ['email'];
			$_data ['createtime'] = date ( 'Y-m-d H:i:s' );
			$_data ['createip'] = get_user_ip ();
			$_data ['loginnum'] = 1;
			$result = $this->add ( $_data );
		}
		// echo $this->getLastSql ();
		return $result;
	}

	/**
	 * 修改密码
	 *
	 * @param unknown $newPassword
	 * @param unknown $oldPassword
	 * @return string
	 */
	public function editPassword($newPassword, $oldPassword) {
		$uid = get_cookie ( 'uid' );
		$userInfo = $this->_getUserInfo ( $uid );
		$ucresult = uc_user_edit ( $userInfo ['username'], $oldPassword, $newPassword );
		if ($ucresult > 0) {
			$result ['status'] = 1;
			$result ['msg'] = '密码更新成功';
		} elseif ($ucresult == - 1) {
			$result ['status'] = 0;
			$result ['msg'] = '旧密码不正确';
		} elseif ($ucresult == - 7) {
			$result ['status'] = 0;
			$result ['msg'] = '没有做任何修改';
		} elseif ($ucresult == - 8) {
			$result ['status'] = 0;
			$result ['msg'] = '该用户受保护无权限更改';
		} else {
			$result ['status'] = 0;
			$result ['msg'] = '未定义错误，请稍后重试';
		}
		return $result;
	}

	/**
	 * 找回密码-重设密码
	 *
	 * @param unknown $uid
	 * @param unknown $password
	 * @return string
	 */
	public function reFindPassword($uid, $password) {
		$userInfo = $this->_getUserInfo ( $uid );
		if (strlen ( $password ) < 6) {
			$result ['status'] = 0;
			$result ['msg'] = '密码长度必须大于6位';
		} elseif (! $userInfo ['username']) {
			$result ['status'] = 0;
			$result ['msg'] = '用户信息获取失败';
		} else {
			$ucresult = uc_user_edit ( $userInfo ['username'], null, $password, null, 1 );
			if ($ucresult > 0) {
				$result ['status'] = 1;
				$result ['msg'] = '密码更新成功';
			} elseif ($ucresult == 0) {
				$result ['status'] = 0;
				$result ['msg'] = '没有做任何改变';
			} elseif ($ucresult == - 1) {
				$result ['status'] = 0;
				$result ['msg'] = '旧密码不正确';
			} elseif ($ucresult == - 7) {
				$result ['status'] = 0;
				$result ['msg'] = '没有做任何修改';
			} elseif ($ucresult == - 8) {
				$result ['status'] = 0;
				$result ['msg'] = '该用户受保护无权限更改';
			} else {
				$result ['status'] = 0;
				$result ['msg'] = '未定义错误，请稍后重试' . $ucresult;
			}
		}
		return $result;
	}

	/**
	 * 找回密码
	 *
	 * @param unknown $email
	 * @return string
	 */
	public function findPassword($email) {
		if (strpos ( $email, '@' )) {
			$where = 'email="' . $email . '"';
		} else {
			$where = 'username="' . $email . '"';
		}
		$userInfo = $this->where ( $where )->find ();
		if (! $userInfo ['uid']) {
			list ( $uid1, $username1, $email1 ) = uc_get_user ( $email );
			if ($uid1) {

				// 添加到本地数据库
				$userInfo ['uid'] = $uid1;
				$userInfo ['username'] = $username1;
				$userInfo ['email'] = $email1;
				$userInfo ['updateip'] = get_user_ip ();
				$userInfo ['updatetime'] = date ( 'Y-m-d H:i:s' );
				$this->saveUser ( $userInfo );
			}
		}
		if (! $userInfo ['uid']) {
			$result ['status'] = 0;
			if (strpos ( $email, '@' )) {
				$result ['msg'] = '找不到您输入的邮箱，换用户名试试';
			} else {
				$result ['msg'] = '您输入的信息不存在';
			}
		} else {
			$overtime = strtotime ( "+2 hours" );
			$overdate = date ( 'Y-m-d H:i:s', $overtime );
			$token = get_token ( $userInfo ['uid'], $overtime );
			$url = C ( 'site_url' ) . '?a=refindpassword&token=' . $token . '&uid=' . intval ( $userInfo ['uid'] );

			$email = new EmailModel ();
			$html = '<div class="main" style="width:650px; margin:0 auto; margin-top:20px; -moz-box-shadow: 2px 2px 10px #909090; -webkit-box-shadow: 2px 2px 10px #909090; box-shadow:2px 2px 15px #909090; min-height:500px; line-height:22px;"><div class="header" style="width:650px; height:53px; overflow:hidden;background-image:url(http://hua-static.fengqiaoju.com/home/images/bodybg.jpg); background-repeat:repeat-x;background-color:#000;"><div class="logo" style="background-image:url(http://hua-static.fengqiaoju.com/home/images/toplogo.jpg); background-repeat:no-repeat; width:155px; height:53px;"><a href="#"></a></div></div><div class="content" style=" word-wrap: break-word; font-size:12px; color:#333;"><img alt="枫桥居" src="http://hua-static.fengqiaoju.com/mobile/images/banner02.jpg" width="100%;" height="140px" /><div style="padding:10px;"><div class="welcome" style="font-weight:bold; margin-top:10px;">尊敬的 ' . $userInfo ['username'] . ':</div><p style="margin:10px 0px; word-wrap: break-word; text-indent:2em;">您好！</p><p style="margin:10px 0px; word-wrap: break-word; text-indent:2em;">此邮箱于' . date ( 'Y-m-d H:i:s' ) . '在枫桥居申请找回密码，由于我们的疏忽使您忘记密码我们深表歉意。</p><p style="margin:10px 0px; word-wrap: break-word; text-indent:2em;">请在' . $overdate . '前点击下面链接找回您的密码（如果不是您本人申请，请忽略此邮件）</p><p><a href="' . $url . '"  target="_blank">' . $url . '</a></p></div></div><div class="footer" style="padding-bottom:15px; font-size:12px;"><span style="margin-left:450px;">枫桥居管理员</span><span style="margin-left:450px;">' . date ( 'Y-m-d' ) . '</span></div></div>';
			$email->send ( $userInfo ['email'], '找回枫桥居密码', $html );
			$arr = explode ( '@', $userInfo ['email'] );
			$emailStr = substr ( $arr [0], 0, 3 ) . '*@' . $arr [1];
			$result ['status'] = 1;
			$result ['msg'] = '打开' . $emailStr . '邮件找回密码';
		}
		return $result;
	}

	/**
	 * 发送激活链接
	 *
	 * @param unknown $email
	 * @return string
	 */
	public function sendActivation($email = '') {
		if ($email) {
			$where = 'email="' . $email . '"';
		} else {
			$uid = get_cookie ( 'uid' );
			$where = 'uid=' . intval ( $uid );
		}
		$userInfo = $this->where ( $where )->find ();

		if (! $userInfo ['uid']) {
			$result ['status'] = 0;
			$result ['msg'] = '用户信息不存在';
		} elseif ($userInfo ['activation'] == 1) {
			$result ['status'] = 0;
			$result ['msg'] = '此账号已经激活';
		} else {
			$overtime = strtotime ( "+30 day" );
			$overdate = date ( 'Y-m-d H:i:s', $overtime );
			$token = get_token ( $userInfo ['uid'], $overtime );
			$url = C ( 'site_url' ) . '?a=doActivation&token=' . $token . '&uid=' . intval ( $userInfo ['uid'] );

			$email = new EmailModel ();

			$html = '<div class="main" style="width:650px; margin:0 auto; margin-top:20px; -moz-box-shadow: 2px 2px 10px #909090; -webkit-box-shadow: 2px 2px 10px #909090; box-shadow:2px 2px 15px #909090; min-height:500px; line-height:22px;"><div class="header" style="width:650px; height:53px; overflow:hidden;background-image:url(http://hua-static.fengqiaoju.com/home/images/bodybg.jpg); background-repeat:repeat-x;background-color:#000;"><div class="logo" style="background-image:url(http://hua-static.fengqiaoju.com/home/images/toplogo.jpg); background-repeat:no-repeat; width:155px; height:53px;"><a href="#"></a></div></div><div class="content" style=" word-wrap: break-word; font-size:12px; color:#333;"><img alt="枫桥居" src="http://hua-static.fengqiaoju.com/mobile/images/banner02.jpg" width="100%;" height="140px" /><div style="padding:10px;"><div class="welcome" style="font-weight:bold; margin-top:10px;">尊敬的 ' . $userInfo ['username'] . ':</div><p style="margin:10px 0px; word-wrap: break-word; text-indent:2em;">您好！</p><p style="margin:10px 0px; word-wrap: break-word; text-indent:2em;">欢迎注册枫桥居！</p><p style="margin:10px 0px; word-wrap: break-word; text-indent:2em;">请在' . $overdate . '前点击下面链接激活您的账号。</p><p><a href="' . $url . '" target="_blank">' . $url . '</a></p></div></div><div class="footer" style="padding-bottom:15px; font-size:12px;"><span style="margin-left:450px;">枫桥居管理员</span><span style="margin-left:450px;">' . date ( 'Y-m-d' ) . '</span></div></div>';
			$email->send ( $userInfo ['email'], '欢迎注册枫桥居，请激活账号。', $html );

			$result ['status'] = 1;
			$result ['msg'] = '激活邮件发送成功';
		}
		return $result;
	}
	public function doActivation($uid) {
		$where = 'uid=' . intval ( $uid );
		$data ['activation'] = 1;
		$rs = $this->where ( $where )->save ( $data );
		if ($rs == false) {
			$result ['status'] = 0;
			$result ['msg'] = '此激活链接无效！可能的原因是：<br>1、您已经成功激活过；<br>2、此链接已经过期。';
		} else {
			$isHave = $this->_isHave ( $uid );
			if ($isHave ['uid']) {
				add_cookie ( 'uid', $uid );
			} else {
				add_cookie ( 'uid', null );
			}
			$result ['status'] = 1;
			$result ['msg'] = '激活成功';
		}
		return $result;
	}
	/**
	 * 判断是否存在
	 *
	 * @param unknown $uid
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, mixed, unknown, string, object>
	 */
	private function _isHave($uid) {
		$result = $this->where ( 'uid=' . intval ( $uid ) )->find ();
		return $result;
	}

	/**
	 * 清除缓存
	 *
	 * @param unknown $uid
	 */
	private function _clearUserCache($uid) {
		$cacheKey = 'user_' . $uid;
		S ( $cacheKey, NULL );
	}
}
